﻿using System;
using System.IO.Pipes;
using System.Security.Principal;
using System.Threading.Tasks;
using Benchmark.Core.Communication.Data.Interface;
using Benchmark.Core.Communication.Data.Stream_Manager;

namespace Benchmark.Core.Communication.Hub.Impl.Pipe.Core
{
   /// <summary>
   /// Should be able to read and write data to Pipe
   /// </summary>
    public class  PipeServer
    {
      
        public byte[] BytesRead { get; set; }
        IStreamManager _streamManager;
       protected string Pipename{ get; set; }
       public bool LastOperationSuccess { get; set; }
       public bool Isconnected;
       public string ServerName;


       protected void Connect(int totalNumberofClients=1,bool useClientStream = false)
        {
            if (useClientStream)
            {
          
              //String pipeNamea = "\\\\" + ServerName + "\\pipe\\" + Pipename;
                var serverStream = new NamedPipeClientStream(ServerName, Pipename, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation);
                _streamManager = new PipeStreamManager(serverStream);
                serverStream.Connect();
                Isconnected = true;

            }

            else
            {
                var serverStream = new NamedPipeServerStream(Pipename, PipeDirection.InOut, totalNumberofClients);
                _streamManager = new PipeStreamManager(serverStream);
                serverStream.WaitForConnection();
                Isconnected = true;

            }
            

        }


       protected async Task<bool> WriteAsyn(byte[] bytesToWrite)
        {
          
            await Task.Factory.StartNew(() =>
             {
                 _streamManager.WriteByte(bytesToWrite);
             }, TaskCreationOptions.PreferFairness);

           return (true);


        }


       protected async Task<byte[]> ReadAsyn()
       {
           byte[] bytesRead = await Task.Factory.StartNew(() =>
           {
               byte[] bytesReadT = _streamManager.ReadByte();

               return (bytesReadT);
           }, TaskCreationOptions.PreferFairness);


           return (bytesRead);
       }
    }
}
